var express = require('express');
var router = express.Router();
var indexDao = require('../dao/index');
var indexRoutes = module.exports;

/**
 * 首页
 * @param  mid    机构id
 * @param  cid    类别id
 * @param  scid   具体课程的id
 *                url/index?
 */
indexRoutes.index = function(req, res) {
    var par = paramAll(req);
    indexDao.getHomeData(par, function(err, result) {
      if(err) return res.json(new ERR(err, 400));
      res.json(new PKG(result));
    })
}
router.get('/index', indexRoutes.index);

/**
 * 访问记录
 * @param  openid
 * @param  avatar
 * @param  url
 * @param  mechanism_id
 * @param  course_id
 * @param  sub_course_id
 * @param  nick
 *
 *        url/index/visit
 */
indexRoutes.visit = function(req, res) {
    var par = paramAll(req);
    indexDao.visit(par, function(err, result) {
        if(err) return res.json(new ERR(err, 400));
        res.json(new PKG(result));
    })
}
router.post('/visit', indexRoutes.visit);

/**
 * 获取身份信息
 * @param  code
 *        url/index/getInfoByCode
 */
indexRoutes.getInfoByCode = function(req, res) {
    var par = paramAll(req);
    if(!par.code) return res.json(new ERR('code不为空！', 400));
    indexDao.getInfoByCode(par, function(err, result) {
        if(err) return res.json(new ERR(err, 400));
        res.json(new PKG(result));
    })
}
router.post('/getInfoByCode', indexRoutes.getInfoByCode);

/**
 * 获取附近机构
 * @param  lon
 * @param  lat
 * @param  size
 *        url/index/getNearbyMechanism
 */
indexRoutes.getNearbyMechanism = function(req, res) {
    var par = paramAll(req);
    if(!par.lon) return res.json(new ERR('经度不为空！', 400));
    if(!par.lat) return res.json(new ERR('维度不为空！', 400));
    if(par.size) par.size = parseInt(par.size);
    indexDao.getNearbyMechanism(par, function(err, result) {
        if(err) return res.json(new ERR(err, 400));
        res.json(new PKG(result));
    })
}
router.post('/getNearbyMechanism', indexRoutes.getNearbyMechanism);

module.exports = router;